package com.asman.vr.dto

import androidx.annotation.MainThread
import androidx.lifecycle.Transformations
import androidx.paging.Config
import androidx.paging.toLiveData
import com.asman.vr.network.Api
import com.asman.vr.network.ApiWorker
import com.asman.vr.network.liveData
import java.util.concurrent.Executor

class ProjectRepository(
        private val api: Api,
        private val workerApi: ApiWorker,
        private val networkExecutor: Executor
) {

    @MainThread
    fun getRecordList(projectId: Long, sort: Int, pageSize: Int): ResourceListing<RecordListData> {
        val sourceFactory = RecordDataSourceFactory(api, projectId, sort, pageSize, networkExecutor)

        val livePagedList = sourceFactory.toLiveData(
            config = Config(
                pageSize = pageSize,
                enablePlaceholders = true,
                prefetchDistance = 3,
                initialLoadSizeHint = pageSize
            ), fetchExecutor = networkExecutor
        )
        val refreshState =
            Transformations.switchMap(sourceFactory.sourceLiveData) { it.initialLoad }
        return ResourceListing(
            pagedList = livePagedList,
            networkState = Transformations.switchMap(sourceFactory.sourceLiveData) {
                it.networkState
            },
            retry = {
                sourceFactory.sourceLiveData.value?.retryAllFailed()
            },
            refresh = {
                sourceFactory.sourceLiveData.value?.invalidate()
            },
            refreshState = refreshState
        )
    }

    @MainThread
    fun getProjectList() = liveData(api.getProjectList())

    @MainThread
    fun getProjectInfo(projectId: Long) = liveData(api.getProjectInfo(projectId))

    @MainThread
    fun sureStartWork(projectId: Long) = liveData(api.sureStartWork(projectId))

    @MainThread
    fun stageApplyPass(projectId: Long, stageSerial: Int) =
        liveData(api.stageApplyPass(projectId, stageSerial))

    @MainThread
    fun getStageList(projectId: Long) = liveData(api.getStageList(projectId))

    @MainThread //获取施工阶段任务列表
    fun getStageTaskList(projectId: Long, stageSerial: Int) = liveData(
        api.getStageTaskList(projectId, stageSerial)
    )

    @MainThread //获取支付阶段任务列表
    fun getPayTaskList(projectId: Long, stageSerial: Int) =
        liveData(api.getPayTaskList(projectId, stageSerial))

    @MainThread
    fun getLiveInfo(projectId: Long) = liveData(api.getLiveInfo(projectId))

    @MainThread
    fun liveTurnCamera(buttonStr: String, projectId: Long) =
        liveData(api.liveTurnCamera(buttonStr, projectId))

    //摄像头拍照
    @MainThread
    fun liveTakePhoto(projectId: Long) = liveData(api.liveTakePhoto(projectId))

    @MainThread
    fun getDrawingList(projectId: Long) = liveData(workerApi.getDrawingList(projectId))
}